package cn.zhiquxing.send;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONUtil;
import cn.zhiquxing.common.enums.IdType;
import cn.zhiquxing.domain.BasicResultVO;
import cn.zhiquxing.domain.ProcessContext;
import cn.zhiquxing.domain.SendTaskModel;
import cn.zhiquxing.domain.TaskInfo;
import cn.zhiquxing.enums.RespStatusEnum;
import cn.zhiquxing.pipeline.BusinessProcess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 后置参数检查
 */
@Slf4j
@Service
public class SendAfterCheckAciton implements BusinessProcess<SendTaskModel> {
    
    public static final String PHONE_REGEX_EXP = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[0-9])|(18[0-9])|(19[1,8,9]))\\\\d{8}$\"";
    
    public static final String EMAIL_REGEX_EXP = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
    
    protected static final Map<Integer, String> CHANNEL_REGEX_EXP = new HashMap<>();
    
    static {
        CHANNEL_REGEX_EXP.put(IdType.PHONE.getCode(), PHONE_REGEX_EXP);
        CHANNEL_REGEX_EXP.put(IdType.EMAIL.getCode(), EMAIL_REGEX_EXP);
    }
    
    @Override
    public void process(ProcessContext<SendTaskModel> context) {
        SendTaskModel sendTaskModel = context.getProcessModel();
        List<TaskInfo> taskInfos = sendTaskModel.getTaskInfos();
        //过滤掉不合法的邮箱或手机号
        filterIllegalReceiver(taskInfos);
        if (CollUtil.isEmpty(taskInfos)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS, "手机号或者邮箱不合法，无有效的发送任务"));
        }
    }


    /**
     * 如果指定类型是手机号，检测输入手机号是否合法
     * 如果指定类型是邮件，检测输入邮件是否合法
     *
     * @param taskInfos
     */
    private void filterIllegalReceiver(List<TaskInfo> taskInfos) {
        Integer idType = CollUtil.getFirst(taskInfos.iterator()).getIdType();
        filter(taskInfos, CHANNEL_REGEX_EXP.get(idType));
    }

    /**
     * 利用正则过滤不合法的接受这
     * @param taskInfos
     * @param regexExp
     */
    private void filter(List<TaskInfo> taskInfos, String regexExp) {
        Iterator<TaskInfo> iterator = taskInfos.iterator();
        
        while (iterator.hasNext()) {
            TaskInfo taskInfo = iterator.next();
            Set<String> illegalPhone = taskInfo.getReceiver().stream().filter(phone -> !ReUtil.isMatch(regexExp, phone)).collect(Collectors.toSet());
            if (CollUtil.isNotEmpty(illegalPhone)) {
                taskInfo.getReceiver().removeAll(illegalPhone);
                log.error("messageTemplateId: {} find illegal receiver: {}", taskInfo.getMessageTemplateId(), JSONUtil.toJsonStr(illegalPhone));
            }
            if (CollUtil.isEmpty(taskInfo.getReceiver())) {
                iterator.remove();
            }
        }
    }
}
